package dao

import (
	"context"
	"fmt"
	"gorm.io/gorm"
)

type ConsumablesDAO struct {
	db *gorm.DB
}

func NewConsumablesDap(db *gorm.DB) *ConsumablesDAO {
	return &ConsumablesDAO{
		db: db,
	}
}

func (dao *ConsumablesDAO) Query(ctx context.Context, a Consumable) ([]Consumable, error) {
	var Consumables []Consumable
	db := dao.db

	if name := a.Name; name != "" {
		name = fmt.Sprintf("%%%v%%", name)
		db = db.WithContext(ctx).Where("name like ?", name)
	}

	err := db.Debug().WithContext(ctx).Find(&Consumables).Error
	if err != nil {
		fmt.Println("query error")
	}
	return Consumables, nil
}

func (dao *ConsumablesDAO) Select(ctx context.Context) ([]Consumable, error) {
	var consumables []Consumable
	db := dao.db

	err := db.Debug().WithContext(ctx).Select("id", "name", "dict_name").Find(&consumables).Error
	if err != nil {
		fmt.Println("query error")
	}
	return consumables, nil
}

type Consumable struct {
	Id       string `gorm:"autoIncrement, primary_key"`
	Name     string `gorm:"name"`
	DictName string `gorm:"dict_name"`
	Stock    string `gorm:"stock"`
}
